package org.csu.jpetstore_users_backend_pj.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.jpetstore_users_backend_pj.dto.GiteeUser;
import org.csu.jpetstore_users_backend_pj.result.CommonResponse;
import org.csu.jpetstore_users_backend_pj.result.ResponseCode;
import org.csu.jpetstore_users_backend_pj.service.GiteeAccessService;
import org.csu.jpetstore_users_backend_pj.service.SmsService;
import org.csu.jpetstore_users_backend_pj.service.UserService;
import org.csu.jpetstore_users_backend_pj.util.CodeUtil;
import org.csu.jpetstore_users_backend_pj.util.JwtUtil;
import org.csu.jpetstore_users_backend_pj.util.ThreadLocalUtil;
import org.csu.jpetstore_users_backend_pj.vo.AccountVO;
import org.csu.jpetstore_users_backend_pj.vo.TokenAndUsername;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping
@CrossOrigin(origins = "http://localhost:5173")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private GiteeAccessService giteeAccessService;


    @PostMapping("/tokens")
    public CommonResponse signon(
            @RequestParam String username,
            @RequestParam String password
    ) {
        AccountVO loginAccount = userService.login(username, password);
        if (loginAccount != null) {
            // 登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", loginAccount.getUsername());
            String token = JwtUtil.GenerateToken(claims);
            return CommonResponse.createForSuccess(ResponseCode.UserLoginSuccess.getCode(),ResponseCode.UserLoginSuccess.getDescription(),token);
        } else {
            // 登录失败
            return CommonResponse.createForError(ResponseCode.UserNameOrPasswordError.getCode(),ResponseCode.UserNameOrPasswordError.getDescription());
        }
    }

    @DeleteMapping("/tokens")
    public CommonResponse signout(HttpSession session){
        AccountVO accountVO = (AccountVO) session.getAttribute("loginAccount");

        if (accountVO != null) {
            String giteeId = accountVO.getGiteeId();
            if (giteeId != null) {
                // 撤销 Gitee 授权（删除 token 字段或其他处理）
                giteeAccessService.revokeToken(giteeId);
            }
        }
        ThreadLocalUtil.remove();
        return CommonResponse.createForSuccess(ResponseCode.UserLoginOutSuccess.getCode(),ResponseCode.UserLoginOutSuccess.getDescription());
    }


    @PostMapping("/SignOnByPhone")
    public CommonResponse signOnByPhone(
            @RequestParam String phone
    ) {

        AccountVO loginAccount = userService.loginByPhone(phone);
        if (loginAccount != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", loginAccount.getUsername());
            ThreadLocalUtil.set(claims);
            String token = JwtUtil.GenerateToken(claims);
            return CommonResponse.createForSuccess(ResponseCode.UserLoginSuccess.getCode(),ResponseCode.UserLoginSuccess.getDescription(),token);
        } else {
            return CommonResponse.createForError(ResponseCode.UserLoginPhoneError.getCode(),ResponseCode.UserLoginPhoneError.getDescription());
        }
    }

    @PostMapping("/users")
    public CommonResponse register(@RequestBody AccountVO account,
                                   @SessionAttribute(value = "giteeUser", required = false) GiteeUser giteeUser
    ) {
        //默认设置
        account.setListOption(true);
        account.setBannerOption(true);
        account.setStatus("OK");
        if(giteeUser!=null){
            account.setGiteeId(giteeUser.getId());
            account.setGiteeAvatar(giteeUser.getAvatarUrl());
            account.setGiteeNickname(giteeUser.getName());
        }
        System.out.println(account);
        userService.register(account, account.getPassword());
        return CommonResponse.createForSuccess(ResponseCode.UserRegisterSuccess.getCode(),ResponseCode.UserRegisterSuccess.getDescription());
    }


    @PostMapping("/captcha")
    @ResponseBody
    public CommonResponse captcha(@RequestParam String phone, HttpSession session) throws Exception {
        String captcha = CodeUtil.generateNumericCaptcha();
        session.setAttribute("lastCaptcha", captcha); // 存储到 Session
        session.setAttribute("lastPhone", phone); // 存储 phone 以验证
        System.out.println("Sent captcha " + captcha + " to phone: " + phone);
        smsService.sendSms(phone,captcha);
        return CommonResponse.createForSuccess(ResponseCode.GetCaptchaSuccess.getCode(),ResponseCode.GetCaptchaSuccess.getDescription(),captcha);
    }

    @GetMapping("/usernameIsExist")
    @ResponseBody // 添加此注解，表示返回的是字符串数据
    public String usernameIsExist(@RequestParam String username){
        if(userService.IsUsernameExist(username)){
            return "Exist";
        }
        else{
            return "not Exist";
        }
    }
    @GetMapping("/phoneIsExist")
    @ResponseBody // 添加此注解，表示返回的是字符串数据
    public String phoneIsExist(@RequestParam String phone){
        if(userService.IsPhoneExist(phone)){
            return "Exist";
        }
        else{
            return "not Exist";
        }
    }
    @GetMapping("/emailIsExist")
    @ResponseBody // 添加此注解，表示返回的是字符串数据
    public String emailIsExist(@RequestParam String email){
        if(userService.IsEmailExist(email)){
            return "Exist";
        }
        else{
            return "not Exist";
        }
    }


}